import { defineStore } from 'pinia'
// 移除实际API调用
import axios from 'axios'


// Mock数据
const mockUsers = [
  { id: 1, first_name: '张三', last_name: '', email: 'zhangsan@example.com', avatar: 'https://randomuser.me/api/portraits/men/1.jpg' },
  { id: 2, first_name: '李四', last_name: '', email: 'lisi@example.com', avatar: 'https://randomuser.me/api/portraits/women/2.jpg' },
  { id: 3, first_name: '王五', last_name: '', email: 'wangwu@example.com', avatar: 'https://randomuser.me/api/portraits/men/3.jpg' },
  { id: 4, first_name: '赵六', last_name: '', email: 'zhaoliu@example.com', avatar: 'https://randomuser.me/api/portraits/women/4.jpg' },
  { id: 5, first_name: '钱七', last_name: '', email: 'qianqi@example.com', avatar: 'https://randomuser.me/api/portraits/men/5.jpg' },
  { id: 6, first_name: '孙八', last_name: '', email: 'sunba@example.com', avatar: 'https://randomuser.me/api/portraits/women/6.jpg' },
  { id: 7, first_name: '周九', last_name: '', email: 'zhoujiu@example.com', avatar: 'https://randomuser.me/api/portraits/men/7.jpg' },
  { id: 8, first_name: '吴十', last_name: '', email: 'wushi@example.com', avatar: 'https://randomuser.me/api/portraits/women/8.jpg' }
]

// Mock axios服务
const mockAxios = {
  // 获取用户列表
  get(url) {
    // 模拟获取用户列表
    if (url.includes('api/users?page=')) {
      // 从 URL 中提取页码和每页数量
      const pageMatch = url.match(/page=(\d+)/)
      const perPageMatch = url.match(/per_page=(\d+)/)
      
      const page = pageMatch ? parseInt(pageMatch[1]) : 1
      const perPage = perPageMatch ? parseInt(perPageMatch[1]) : 6
      
      const start = (page - 1) * perPage
      const end = start + perPage
      const paginatedUsers = mockUsers.slice(start, end)
      
      return Promise.resolve({
        data: {
          data: paginatedUsers,
          total: mockUsers.length,
          page,
          per_page: perPage,
          total_pages: Math.ceil(mockUsers.length / perPage)
        }
      })
    }
    
    // 模拟获取单个用户
    if (url.match(/api\/users\/\d+/)) {
      const userId = parseInt(url.split('/').pop())
      const user = mockUsers.find(u => u.id === userId)
      
      if (!user) {
        return Promise.reject(new Error('用户不存在'))
      }
      
      return Promise.resolve({
        data: {
          data: user
        }
      })
    }
    
    // 如果没有匹配的路由
    return Promise.reject(new Error('无效的请求URL'))
  },
  
  // 创建用户
  post(url, userData) {
    if (url === 'https://reqres.in/api/users') {
      // 生成新ID
      const newId = Math.max(...mockUsers.map(u => u.id)) + 1
      const newUser = { id: newId, ...userData }
      
      // 添加到mock数据中
      mockUsers.push(newUser)
      
      return Promise.resolve({
        data: newUser
      })
    }
    
    return Promise.reject(new Error('无效的请求URL'))
  },
  
  // 更新用户
  put(url, userData) {
    if (url.match(/api\/users\/\d+/)) {
      const userId = parseInt(url.split('/').pop())
      const index = mockUsers.findIndex(u => u.id === userId)
      
      if (index === -1) {
        return Promise.reject(new Error('用户不存在'))
      }
      
      // 更新用户数据
      const updatedUser = { ...mockUsers[index], ...userData }
      mockUsers[index] = updatedUser
      
      return Promise.resolve({
        data: updatedUser
      })
    }
    
    return Promise.reject(new Error('无效的请求URL'))
  },
  
  // 删除用户
  delete(url) {
    if (url.match(/api\/users\/\d+/)) {
      const userId = parseInt(url.split('/').pop())
      const index = mockUsers.findIndex(u => u.id === userId)
      
      if (index === -1) {
        return Promise.reject(new Error('用户不存在'))
      }
      
      // 从数组中删除
      mockUsers.splice(index, 1)
      
      return Promise.resolve({
        status: 204
      })
    }
    
    return Promise.reject(new Error('无效的请求URL'))
  }
}

// 定义一个使用axios的用户管理store
export const useUserStore = defineStore('users-axios-composition', {
  state: () => ({
    // 用户列表
    users: [],
    // 加载状态
    loading: false,
    // 错误信息
    error: null,
    // 当前选中的用户
    currentUser: null,
    // 分页信息
    pagination: {
      page: 1,
      perPage: 6,
      total: 0
    }
  }),
  
  getters: {
    // 获取用户总数
    totalUsers(state) {
      return state.users.length
    },
    
    // 获取是否有选中的用户
    hasSelectedUser(state) {
      return state.currentUser !== null
    }
  },
  
  actions: {
    // 获取用户列表
    async fetchUsers() {
      this.loading = true
      this.error = null
      
      try {
        const response = await mockAxios.get(`api/users?page=${this.pagination.page}&per_page=${this.pagination.perPage}`)
        this.users = response.data.data
        this.pagination.total = response.data.total
        return response.data
      } catch (error) {
        this.error = error.message || '获取用户列表失败'
        console.error('获取用户列表失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 获取单个用户详情
    async fetchUserById(userId) {
      this.loading = true
      this.error = null
      
      try {
        const response = await mockAxios.get(`api/users/${userId}`)
        this.currentUser = response.data.data
        return response.data.data
      } catch (error) {
        this.error = error.message || '获取用户详情失败'
        console.error('获取用户详情失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 创建新用户
    async createUser(userData) {
      this.loading = true
      this.error = null
      
      try {
        const response = await mockAxios.post('api/users', userData)
        // 将新用户添加到列表中
        this.users.push(response.data)
        return response.data
      } catch (error) {
        this.error = error.message || '创建用户失败'
        console.error('创建用户失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 更新用户信息
    async updateUser(userId, userData) {
      this.loading = true
      this.error = null
      
      try {
        const response = await mockAxios.put(`api/users/${userId}`, userData)
        
        // 更新用户列表中的用户信息
        const index = this.users.findIndex(user => user.id === userId)
        if (index !== -1) {
          this.users[index] = { ...this.users[index], ...response.data }
        }
        
        // 如果当前选中的用户就是被更新的用户，也更新currentUser
        if (this.currentUser && this.currentUser.id === userId) {
          this.currentUser = { ...this.currentUser, ...response.data }
        }
        
        return response.data
      } catch (error) {
        this.error = error.message || '更新用户失败'
        console.error('更新用户失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 删除用户
    async deleteUser(userId) {
      this.loading = true
      this.error = null
      
      try {
        await mockAxios.delete(`api/users/${userId}`)
        
        // 从用户列表中移除该用户
        this.users = this.users.filter(user => user.id !== userId)
        
        // 如果当前选中的用户就是被删除的用户，清空currentUser
        if (this.currentUser && this.currentUser.id === userId) {
          this.currentUser = null
        }
        
        return { success: true }
      } catch (error) {
        this.error = error.message || '删除用户失败'
        console.error('删除用户失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 设置当前页码
    setPage(page) {
      this.pagination.page = page
      // 获取新页码的数据
      return this.fetchUsers()
    },
    
    // 清空当前选中的用户
    clearCurrentUser() {
      this.currentUser = null
    },
    
    // 重置store状态
    resetState() {
      this.users = []
      this.loading = false
      this.error = null
      this.currentUser = null
      this.pagination.page = 1
    }
  }
})
